package com.lzy.handle.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzy.security.LoginUser;
import com.lzy.utils.TokenUtil;
import com.lzy.utils.StringUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lyw
 * @Date 2023/2/1-下午2:56
 */
@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

  @Autowired
  private TokenUtil tokenUtil;

  @SneakyThrows
  @Override
  public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    String token = tokenUtil.getToken(request);
    LoginUser loginUser = tokenUtil.getLoginUser(token);
    if (StringUtil.isNotNull(loginUser)) {
      // 删除用户缓存记录
      tokenUtil.delLoginUser(loginUser.getUser().getUserId(), token);
    }
    Map<String,Object> result = new HashMap<>();
    result.put("msg", "注销成功！");
    result.put("status", 200);
    response.setContentType("application/json;charset=UTF-8");
    String string = new ObjectMapper().writeValueAsString(result);
    response.getWriter().println(string);
  }
}
